package com.xxl.sso.server.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.icom.sso.mapper.DepartmentMapper;
import com.icom.sso.util.RetKit;
import com.xxl.sso.core.entity.PageData;
import com.xxl.sso.server.core.model.BackTree;
import com.xxl.sso.server.core.model.Department;
import com.xxl.sso.server.service.DepartmentService;

@Service
public class DepartmentServiceImpl implements DepartmentService {
	@Autowired
	DepartmentMapper departmentMapper;

	@Override
	public PageData<Department> pageFindDept(Integer page, Integer rows, String dptId, String name, String no) {
		// TODO Auto-generated method stub

		List<Department> listAll = departmentMapper.findDepts(dptId, name, no);

		// 从第几条数据开始
		int firstIndex = (page - 1) * rows;
		// 到第几条数据结束
		int lastIndex = page * rows;
		// 截取查询页的数据
		List<Department> list = new ArrayList<>();
		if (lastIndex <= listAll.size()) {
			list = listAll.subList(firstIndex, lastIndex);
		} else {
			list = listAll.subList(firstIndex, listAll.size());
		}

		return new PageData<Department>(list, page, rows, listAll.size());
	}

	@Override
	public List<BackTree> findDeptTree() {
		// TODO Auto-generated method stub
		List<BackTree> list = departmentMapper.findDeptTree();

		return list;
	}

	@Override
	public Department findDeptById(String id) {
		// TODO Auto-generated method stub
		Department department = departmentMapper.findDeptById(id);

		return department;
	}

	@Override
	public RetKit<String> saveDept(Department department) {
		// TODO Auto-generated method stub
		RetKit<String> ret = new RetKit<String>(null);
		try {
			int row = departmentMapper.saveDept(department);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ret.setFail();
			ret.setMsg("新增部门异常！");
		}

		return ret;
	}

	@Override
	public RetKit<String> saveEditInfo(Department department) {
		// TODO Auto-generated method stub
		RetKit<String> ret = new RetKit<String>(null);
		try {
			int row = departmentMapper.saveEditInfo(department);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ret.setFail();
			ret.setMsg("修改部门信息异常！");
		}

		return ret;
	}

	@Override
	public RetKit<String> delDept(String id) {
		// TODO Auto-generated method stub
		RetKit<String> ret = new RetKit<String>(null);
		try {
			int row = departmentMapper.delDept(id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ret.setFail();
			ret.setMsg("删除部门异常！");
		}

		return ret;
	}

	@Override
	public List<Department> findDepts() {
		// TODO Auto-generated method stub
		List< Department> list = departmentMapper.findDepartments();
		
		return list;
	}

}
